<template>
  <!-- 弹窗 -->
  <div class="mydialog">
    <el-dialog
      :title="title"
      :visible.sync="poshow"
      :before-close="handleClose"
      width="30%"
    >
      <div>
        <el-row :gutter="20">
          <el-col
            :span="12"
            :style="{
              height: '350px',
              overflowX: 'hidden',
              overflowY: 'auto',
            }"
          >
            <div class="colname">可选择</div>
            <el-input
              v-model="filterText"
              placeholder="输入关键字进行过滤"
              class="colinput"
            />

            <el-tree
              ref="xtree"
              class="filter-tree"
              :data="data"
              :props="defaultProps"
              node-key="id"
              show-checkbox
              :highlight-current="true"
              :filter-node-method="filterNode"

              @check="handleCheckChange"
              @check-change="handleChange"
            />
            <!--  :default-checked-keys="defaultList" -->
          </el-col>
          <el-col
            :span="12"
            :style="{
              height: '350px',
              overflowX: 'hidden',
              overflowY: 'auto',
            }"
          >
            <div class="colname">已选中</div>
            <el-input
              v-model="filterText"
              style="visibility: hidden"
              placeholder="输入关键字进行过滤"
              class="colinput"
            />
            <div class="userbox">
              <div v-for="(item, index) in userGroupList" :key="item.id" class="useritem">
                <span class="choiceConItem">{{ setStr(item.title) }}</span>
                <i class="el-icon-close fs_12 color-blue ico" @click="deleteItem(item, index)" />
              </div>
            </div>
          </el-col>
        </el-row>
      </div>

      <div slot="footer" class="dialog-footer">
        <el-button @click="selectAll">全 选</el-button>
        <el-button @click="isON()">取 消</el-button>
        <el-button type="primary" @click="isOK()">确 定</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
export default {
  props: {
    poshow: {
      type: Boolean,
      default: false
    },
    type: {
      type: String,
      default: ''
    },
    title: {
      type: String,
      default: ''
    },
    index: {
      type: Number,
      default: 0
    },
    echo: {
      type: Array,
      default: () => {
        return []
      }
    }
  },
  data() {
    return {
      filterText: '', // 搜索
      defaultList: [],
      data: [],
      starr: [], // 提交
      checkNodeList: [], // 选中的
      userGroupList: [], // 右侧展示的
      defaultProps: {
        children: 'childrenDepartment',
        label: 'title'
      },
      checkAll: false
    }
  },
  computed: {
    setStr() {
      return function(str) {
        if (str.length >= 4) {
          str = str.slice(0, 4) + '...'
          return str
        } else {
          return str
        }
      }
    }
  },
  watch: {
    filterText(val) {
      this.$refs.xtree.filter(val)
    },
    type(newval) {
      if (newval) {
        this.getList(newval)
      }
    },
    data(newval) {

    },
    poshow(newval) {
      if (newval) {
        this.defaultList = []
        this.echo.map((item) => {
          if (this.type === '8') {
            this.defaultList.push(item.nodeHandlerId)
          } else {
            this.defaultList.push(item.nodeHandlerId)
          }
        })
        this.$nextTick(() => {
          const that = this
          setTimeout(() => {
            this.defaultList.forEach(value => {
              that.$refs.xtree.setChecked(value, true, false)
            })
          }, 500)
        })
        this.userGroupList = this.echo
        this.starr = this.userGroupList
      } else {
        this.$nextTick(function() {
          this.$refs.xtree.setCheckedKeys([])
          var nodes = this.$refs.xtree.store.nodesMap
          for (var i in nodes) {
            nodes[i].expanded = false
          }
        })
        this.filterText = ''
        this.userGroupList = []
        this.defaultList = []
        this.checkNodeList = []
        this.starr = []
      }
    }

  },
  mounted() {

  },
  created() {
    this.getList(this.type)
  },
  methods: {
    // 截取字符串
    stringInterception(str) {
      if (str.length >= 10) {
        str = str.slice(0, 10) + '...'
        return str
      } else {
        str = str.substring(str.length - 1) === ',' ? str.substring(0, str.length - 1) : str

        return str
      }
    },
    // 获取列表
    async getList(newval) {
      this.data = []
      try {
        if (newval === '1' || newval === '4') {
          const res = await this.$Http.getdDepartment()
          if (res.code === 200) {
            for (let i = 0; i < res.result.length; i++) {
              res.result[i].level = 1
              if (res.result[i].childrenDepartment) {
                for (let j = 0; j < res.result[i].childrenDepartment.length; j++) {
                  res.result[i].childrenDepartment[j].level = 2
                  if (res.result[i].childrenDepartment[j].childrenDepartment) {
                    if (res.result[i].childrenDepartment[j].childrenDepartment.length > 0) {
                      for (let k = 0; k < res.result[i].childrenDepartment[j].childrenDepartment.length; k++) {
                        res.result[i].childrenDepartment[j].childrenDepartment[k].level = 3
                      }
                    }
                  }
                }
              }
            }
            this.data = res.result
          }
        } else if (newval === '2' || newval === '5' || newval === '7' || newval === '9') {
          const res = await this.$Http.getRoleList()
          if (res.code === 200) {
            for (let i = 0; i < res.result.length; i++) {
              this.data.push({
                title: res.result[i].name,
                id: res.result[i].id,
                level: 1,
                roleLevel: res.result[i].level
              })
            }
          }
        } else if (newval === '3' || newval === '6' || newval === '8' || newval === '10') {
          // 选人员
          const res = await this.$Http.getUserList()
          if (res.code === 200) {
            for (let i = 0; i < res.result.length; i++) {
              res.result[i].level = 1
              if (res.result[i].childrenUser) {
                if (res.result[i].childrenUser.length > 0) {
                  res.result[i].childrenUser.map((item) => {
                    res.result[i].childrenDepartment.push({
                      level: 2,
                      id: item.id,
                      title: item.nickName,
                      hontDepartmentId: item.departmentId,
                      roleLevel: item.roleLevel
                    })
                  })
                }
              }

              if (res.result[i].childrenDepartment) {
                for (
                  let j = 0;
                  j < res.result[i].childrenDepartment.length;
                  j++
                ) {
                  res.result[i].childrenDepartment[j].level = 2

                  if (res.result[i].childrenDepartment[j].childrenUser) {
                    if (
                      res.result[i].childrenDepartment[j].childrenUser.length >
                      0
                    ) {
                      res.result[i].childrenDepartment[j].childrenUser.map((item) => {
                        if (res.result[i].childrenDepartment[j].childrenDepartment) {
                          res.result[i].childrenDepartment[j].childrenDepartment.push({
                            level: 3,
                            id: item.id,
                            title: item.nickName,
                            hontDepartmentId: item.departmentId,
                            roleLevel: item.roleLevel
                          })
                        }
                      }
                      )
                    }
                  }

                  if (res.result[i].childrenDepartment[j].childrenDepartment) {
                    if (
                      res.result[i].childrenDepartment[j].childrenDepartment
                        .length > 0
                    ) {
                      for (
                        let k = 0;
                        k <
                        res.result[i].childrenDepartment[j].childrenDepartment
                          .length;
                        k++
                      ) {
                        res.result[i].childrenDepartment[j].childrenDepartment[
                          k
                        ].level = 3

                        if (
                          res.result[i].childrenDepartment[j]
                            .childrenDepartment[k].childrenUser
                        ) {
                          if (
                            res.result[i].childrenDepartment[j]
                              .childrenDepartment[k].childrenUser.length > 0
                          ) {
                            res.result[i].childrenDepartment[
                              j
                            ].childrenDepartment[k].childrenUser.map((item) => {
                              if (
                                res.result[i].childrenDepartment[j]
                                  .childrenDepartment[k].childrenDepartment
                              ) {
                                res.result[i].childrenDepartment[
                                  j
                                ].childrenDepartment[k].childrenDepartment.push(
                                  {
                                    level: 4,
                                    id: item.id,
                                    title: item.nickName,
                                    hontDepartmentId: item.departmentId,
                                    roleLevel: item.roleLevel
                                  }
                                )
                              }
                            })
                          }
                        }
                      }
                    }
                  }
                }
              }
            }
            this.data = res.result
          }
        }
      } catch (err) {
        console.log('err', err)
      }
    },
    filterNode(value, data) {
      if (!value) return true
      return data.title.indexOf(value) !== -1
    },
    // 全选
    selectAll() {
      this.checkAll = !this.checkAll
      if (this.checkAll) {
        // 全选
        this.$nextTick(() => {
          // 这个如果要默认全选就必须加，否则会报错“setCheckedNodes”未定义
          this.$refs.xtree.setCheckedNodes(this.data)
          this.checkNodeList = this.$refs.xtree.getCheckedNodes()
          this.userGroupList = this.checkNodeList
        })
      } else {
        // 取消选中
        this.$nextTick(() => {
          this.$refs.xtree.setCheckedKeys([])
          this.userGroupList = []
        })
      }
    },
    handleClose() {
      this.$emit('handleClose', this.index)
    },
    isON() {
      this.$emit('handleClose', this.index)
    },
    isOK() {
      var str = ''
      this.starr.map((item) => {
        str += item.title + ','
      })
      console.log('this.starr', this.starr)
      this.$emit(
        'handleDetermine',
        this.stringInterception(str),
        this.starr,
        this.index
      )
    },
    handleChange(data, checked, indeterminate) {
      const res = this.$refs.xtree.getCheckedNodes()
      this.starr = []

      res.forEach((item) => {
        if (this.type === '8') {
          this.starr.push({
            title: item.title,
            nodeHandlerId: item.id, // 用户id
            hontDepartmentId: item.hontDepartmentId, // 部门id （用户时填写）,
            roleLevel: item.roleLevel // 等级
          })
        } else if (this.type === '7') {
          this.starr.push({
            title: item.title,
            nodeHandlerId: item.id, // 用户id
            hontDepartmentId: item.hontDepartmentId, // 部门id （用户时填写）,
            roleLevel: item.roleLevel // 等级
          })
        } else {
          this.starr.push({
            nodeHandlerId: item.id,
            title: item.title
          })
        }
      })
    },

    checkRequired(currentData, checkedKeys, halfCheckedNodes) {
      const currentKey = currentData.code
      const currentType = currentData.type
      if (checkedKeys.includes(currentKey)) {
        // 当前选中
        this.fetchCheckedNodeParent(
          halfCheckedNodes,
          currentKey,
          this.setRequiredNodeChecked
        )
      } else if (currentType) {
        // 取消选中，但当前项是必选项（如果取消勾选的是列表，那么其余同级节点全部取消勾选）
        this.fetchCheckedNodeParent(
          halfCheckedNodes,
          currentKey,
          this.setNodeUnChecked
        )
      }
    },
    // 点击节点
    handleCheckChange(data, node) {
      this.checkRequired(data, node.checkedKeys, node.halfCheckedNodes)
      this.checkNodeList = this.$refs.xtree.getCheckedNodes()
      this.userGroupList = this.checkNodeList
    },
    deleteItem(item, index) {
      this.userGroupList.splice(index, 1)
      this.$refs.xtree.setChecked(item.nodeHandlerId)
      this.$forceUpdate()
    }
  }
}
</script>

<style lang="scss" scoped>
.mydialog {
  .colname {
    font-size: 15px;
    font-weight: 600;
    margin-bottom: 8px;
  }
  .colinput {
    margin-bottom: 10px;
  }
  .userbox {
    display: flex;
    align-items: center;
    justify-content: space-between;
    flex-wrap: wrap;
  }
  .userbox:after {
    content: "";
    width: 32%;
    height: 0px;
    visibility: hidden;
  }
  .useritem {
    text-align: center;
    box-sizing: border-box;
    height: 40px;
    line-height: 40px;
    background: rgba(175, 238, 238, 0.8);
    font-size: 12px;
    color: #000;
    margin: 0 20px 20px 0;
    width: calc((100% - 60px) / 3);
    border-radius: 2px;
    position: relative;
    .ico {
      font-size: 13px;
      position: absolute;
      top: 2px;
      right: 2px;
    }
  }
}
</style>
